package arithmetic.leetCode;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串 ""。
 * <p>
 * 示例 1:
 * <p>
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 * 示例 2:
 * <p>
 * 输入: ["dog","racecar","car"]
 * 输出: ""
 * 解释: 输入不存在公共前缀。
 * 说明:
 * <p>
 * 所有输入只包含小写字母 a-z 。
 *
 * @author dycong
 * @date 2019/12/2 14:27
 */
public class LongestCommonPrefix_14 {
    public static void main(String[] args) {
        LongestCommonPrefix_14 longestCommonPrefix_14 = new LongestCommonPrefix_14();
//        String[] strs = {"flower", "flow", "flight"};
        String[] strs = {"abca","aba","aaab"};
        System.out.println(longestCommonPrefix_14.longestCommonPrefix(strs));
    }

    public String longestCommonPrefix(String[] strs) {
        String shortestSunString = shortestSunString(strs);

        //todo 外层对最短字符串遍历
        for (int i = 0; i < shortestSunString.length(); i++) {
            for (int j = 0; j < strs.length; j++) {
                if (shortestSunString.charAt(i) != strs[j].charAt(i)) {
                    return shortestSunString.substring(0, i);
                }
            }
        }
        return shortestSunString;
    }

    /**
     * 找到最短字串
     *
     * @param strings
     * @return
     */
    private String shortestSunString(String[] strings) {
        if (strings.length == 0) {
            return "";
        }

        String res = strings[0];

        for (String string : strings) {
            if (res.length() > string.length()) {
                res = string;
            }
        }
        return res;
    }

}
